import {createRouter, createWebHistory} from 'vue-router';
import root from './root';

import { ADMIN_USER_TOKEN, USER_TOKEN } from '/@/store/constants'



// 路由权限白名单
const allowList = ['adminLogin', 'login', 'register', 'portal', 'search', 'detail', '403', '404']
// 前台登录地址
const loginRoutePath = '/index/login'
// 后台登录地址
const adminLoginRoutePath = '/adminLogin'


const router = createRouter({
  history: createWebHistory(),
  routes: root,
});

router.beforeEach(async (to, from, next) => {
  console.log(to, from);

  /** 后台路由 **/
  if (to.path.startsWith('/admin')) {
    if (localStorage.getItem(ADMIN_USER_TOKEN)) {
      if (to.path === adminLoginRoutePath) {
        return next({ path: '/' });
      } else {
        return next();
      }
    } else {
      if (allowList.includes(to.name as string)) {
        // 在免登录名单，直接进入
        return next();
      } else {
        return next({ path: adminLoginRoutePath, query: { redirect: to.fullPath } });
      }
    }
  }

  /** 前台路由 **/
  if (to.path.startsWith('/index')) {
    if (localStorage.getItem(USER_TOKEN)) {
      if (to.path === loginRoutePath) {
        return next({ path: '/' });
      } else {
        return next();
      }
    } else {
      if (allowList.includes(to.name as string)) {
        // 在免登录名单，直接进入
        return next();
      } else {
        return next({ path: loginRoutePath, query: { redirect: to.fullPath } });
      }
    }
  }

  // 如果路径不以 '/admin' 或 '/index' 开头，仍需调用 next()
  next();
});

router.afterEach((_to) => {
  // 回到顶部
  document.getElementById("html")?.scrollTo(0, 0)
});

// const routes = [
//   // {
//   //   path: '/chat-list',
//   //   name: 'ChatList',
//   //   component: () => import('/@/views/index/components/ChatList.vue')
//   // },
//   // {
//   //   path: '/chat-box/:targetId',
//   //   name: 'ChatBox',
//   //   component: () => import('/@/views/index/components/ChatBox.vue'),
//   //   props: true,
//   // },

  

// ];

export default router;
